/*
 *  $Id: Cursor.cs 1214 2010-11-24 10:30:04Z thenn.erannor $
 *	This file is a part of Ragima CCG.
 *	(C) 2008-2010 Ragima development group.
 *
 *	Licensed under the terms of the GNU GPL License version 2.
 *
 */

using AgateLib.DisplayLib;
using AgateLib.Geometry;
using AgateLib.InputLib;

using Nereal.Serialization;

using Ragima.Helper;

namespace Ragima.UI {
    /// <summary>
    /// Класс, представляющий собой определенный курсор мыши и отрисовывающий его.
    /// </summary>
    public sealed class Cursor {
        private static Resource<CursorSurface> Cursors = new Resource<CursorSurface>("Cursors");

        private string _id;
        private CursorSurface _cursors;
        private Surface _surface;
        private CursorDescriptor _descriptor;

        public Cursor(string id) : this(id, Cursors.Data) {
        }
        public Cursor(string id, CursorSurface cursors) {
            _id = id;
            _cursors = cursors;
            _surface = null;
            _descriptor = null;
        }

        public string Id {
            get { return _id; }
        }

        public Surface Surface {
            get { return _surface ?? (_surface = _cursors != null ? _cursors.Surface : null); }
        }

        public CursorDescriptor Descriptor {
            get { return _descriptor ?? (_descriptor = _cursors != null ? _cursors.Descriptors.GetDescriptor(_id) : null); }
        }

        public void Draw() {
            var desc = Descriptor;
            var pos = Mouse.Position.Sub(desc.Offset);
            var number = Mouse.Buttons[Mouse.MouseButtons.Primary] ? 1 : 0;
            desc.Draw(number, Surface, pos);
        }

        public static implicit operator Cursor(string id) {
            return !string.IsNullOrEmpty(id) ? new Cursor(id) : null;
        }

        public sealed class IdResolver : IKeyResolver<string, Cursor> {
            public string ResolveKey(Cursor value) {
                return value.Id;
            }

            public Cursor ResolveValue(string key) {
                return key;
            }
        }
    }
}
